<template>
<div class="homecat">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
    >
      <van-card
        v-for="lis in lists"
        :key="lis.id"
        :title="lis.title"
        :thumb="lis.image"
        @click-thumb="jumpToDetail(lis.id)"
      >
      <template #desc>
          <div class="card-desc">{{lis.rankingTag}}</div>
        </template>
        <template #tags>
          <div>全天热卖 NO.{{lis.dataoke.dailyRanking}}</div>
          <div>
            <span>￥{{lis.price | money}}</span>
            <span>原价：{{lis.originPrice | money}}</span>
          </div>
        </template>
        <template #price>
          <van-tag v-if="lis.couponValue" plain type="primary" color="#f00">{{lis.couponValue}}</van-tag>
        </template>
        <template #num>
          <div>
            <van-icon
              :style="{marginLeft: '12px'}"
              name="cart-o"
              color="#F00"
              size="18"
              @click="addToCart(lis)"
            />
          </div>
        </template>
      </van-card>
     </van-list>
</div>
</template>

<script>
import { getSubCategories } from '@/api/category'
export default {
  name: 'HomeCat',
  data() {
    return {
      loading: false, // 当前是否正在加载列表数据
      finished: false, // 所有列表数据是否加载完毕
      nextIndex: 0, // 列表数据加载时下一页数据起始索引
      lists: [],
    }
  },
  // props: ['lists'],
  mounted() {
  },
  methods: {
    // 跳转到详情页面：编程式的导航
    jumpToDetail(id) {
      this.$router.push(`/detail?id=${id}`)
    },
    // 加入购物车
    addToCart(product) {
      console.log('add to cart', product)
      const { id, title, image, price, qunTitle } = product
      // 当前选购商品
      const curr = {
        id,
        title,
        image,
        price,
        desc: qunTitle,
        amount: 1,
      }
      // 保存到购物车数组中
      // 通过提交 mutation 来保存
      this.$store.commit('add', curr)
    },
  },
  watch: { // 监听路由变化
    $route: {
      handler(newVal, oldVal) {
        console.log('路由变化了,', newVal.params.hid)
        // 根据父级分类id查询子分类
        getSubCategories(newVal.params.hid)
          .then(data => {
            console.log(data)
            // console.log(lists)
            this.lists = data.items.list
            this.nextIndex = data.nextIndex
            this.loading = false
            this.finished = data.isEnd
          })
          .catch(err => console.lor('err:', err))
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style>

</style>
